package com.example.mybatisplusdemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.mybatisplusdemo.common.JsonResponse;
import com.example.mybatisplusdemo.common.utls.SessionUtils;
import com.example.mybatisplusdemo.model.domain.Favorite;
import com.example.mybatisplusdemo.model.domain.User;
import com.example.mybatisplusdemo.mapper.UserMapper;
import com.example.mybatisplusdemo.model.dto.YearUserActivityDTO;
import com.example.mybatisplusdemo.model.dto.YesrCountDTO;
import com.example.mybatisplusdemo.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.Random;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lxp
 * @since 2025-07-04
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    private static final Random RANDOM = new Random();

    public boolean isUsernameRepeat(String username) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        return userMapper.selectCount(wrapper) > 0;
    }

    //随机生成10位账号
    public String generateUsername() {
        StringBuilder sb = new StringBuilder(10);
        sb.append(RANDOM.nextInt(9) + 1);
        for (int i = 1; i < 10; i++) {
            sb.append(RANDOM.nextInt(10));
        }
        return sb.toString();
    }

    @Override
    public User loginByUsername(User user) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, user.getUsername())
                .eq(User::getPassword, user.getPassword());
        User one = userMapper.selectOne(queryWrapper);
        SessionUtils.saveCurrentUserInfo(one);
        return one; // 仅返回查询结果
    }

    @Override
    public User loginByPhone(User user) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, user.getPhone())
                .eq(User::getPassword, user.getPassword());
        User one = userMapper.selectOne(queryWrapper);
        SessionUtils.saveCurrentUserInfo(one);
        return one; // 仅返回查询结果
    }

    @Override
    public User loginByEmail(User user) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmail, user.getEmail())
                .eq(User::getPassword, user.getPassword());
        User one = userMapper.selectOne(queryWrapper);
        SessionUtils.saveCurrentUserInfo(one);
        return one; // 仅返回查询结果
    }

    @Override
    public User loginByWechat(User user) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getWechatId, user.getWechatId())
                .eq(User::getPassword, user.getPassword());
        User one = userMapper.selectOne(queryWrapper);
        SessionUtils.saveCurrentUserInfo(one);
        return one; // 仅返回查询结果
    }

    @Override
    public boolean registerByPhone(User user) {
        LambdaQueryWrapper<User> wrapperPhone = new LambdaQueryWrapper<>();
        wrapperPhone.eq(User::getPhone, user.getPhone());
        if (userMapper.selectCount(wrapperPhone) > 0)
            return false;
        //后台生成账号
        String username = generateUsername();
        while (isUsernameRepeat(username))
            username = generateUsername();
        user.setUsername(username);
        user.setRegisteredAt(LocalDate.now());
        user.setStatus((byte)1);
        user.setReviewCount(0);
        userMapper.insert(user);
        SessionUtils.saveCurrentUserInfo(user);
        return true;
    }

    @Override
    public boolean registerByEmail(User user) {
        LambdaQueryWrapper<User> wrapperEmail = new LambdaQueryWrapper<>();
        wrapperEmail.eq(User::getEmail, user.getEmail());
        if (userMapper.selectCount(wrapperEmail) > 0)
            return false;
        //后台生成账号
        String username = generateUsername();
        while (isUsernameRepeat(username))
            username = generateUsername();
        user.setUsername(username);
        user.setRegisteredAt(LocalDate.now());
        user.setStatus((byte)1);
        user.setReviewCount(0);
        userMapper.insert(user);
        SessionUtils.saveCurrentUserInfo(user);
        return true;
    }

    @Override
    public boolean registerByWechat(User user) {
        LambdaQueryWrapper<User> wrapperWechat = new LambdaQueryWrapper<>();
        wrapperWechat.eq(User::getWechatId, user.getWechatId());
        if (userMapper.selectCount(wrapperWechat) > 0)
            return false;
        //后台生成账号
        String username = generateUsername();
        while (isUsernameRepeat(username))
            username = generateUsername();
        user.setUsername(username);
        user.setRegisteredAt(LocalDate.now());
        user.setStatus((byte)1);
        user.setReviewCount(0);
        userMapper.insert(user);
        SessionUtils.saveCurrentUserInfo(user);
        return true;
    }

    //用户注册方法
    @Override
    public boolean userRegister(User user) {

        //检查手机号是否存在
        if (StringUtils.isNotBlank(user.getPhone())) {
            if (userMapper.selectOne(new QueryWrapper<User>().eq("phone", user.getPhone())) != null) {
                throw new RuntimeException("手机号已被注册");
            }
        }

        //检查邮箱是否存在
        if (StringUtils.isNotBlank(user.getEmail())) {
            if (userMapper.selectOne(new QueryWrapper<User>().eq("email", user.getEmail())) != null) {
                throw new RuntimeException("邮箱已被注册");
            }
        }

        //创建新用户
        User newUser = new User();
        String username = generateUsername();
        while (isUsernameRepeat(username))
            username = generateUsername();
        newUser.setUsername(username);
        newUser.setNickname(user.getNickname());
        newUser.setPassword(user.getPassword());
        newUser.setPhone(user.getPhone());
        newUser.setEmail(user.getEmail());
        newUser.setWechatId(user.getWechatId());

        //设置默认字段
        newUser.setNickname(user.getUsername()); // 默认昵称同用户名
        newUser.setGender((byte) 0); // 默认性别
        newUser.setAvatarUrl("default_avatar_url"); // 默认头像
        newUser.setRegisteredAt(LocalDate.now());
        newUser.setStatus((byte) 1); // 状态：1-启用
        newUser.setDeleted(false);

        //插入数据库
        return userMapper.insert(newUser) > 0;
    }

    @Override
    public Page<User> listUsers(Page<User> page, User user) {
        return userMapper.listUsers(page, user);
    }

    @Override
    public boolean freezeById(Long id) {
        return userMapper.freeById(id);
    }

    @Override
    public boolean unfreezeById(Long id) {
        return userMapper.unfreezeById(id);
    }

    @Override
    public User getOtherUserInfo(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public List<YesrCountDTO> getAnnualRegistrations(Integer startYear, Integer endYear) {
        return userMapper.getAnnualRegistrations(startYear, endYear);
    }

    @Override
    public List<YearUserActivityDTO> getUserActivityByYear(Integer startYear, Integer endYear) {
        return userMapper.getUserActivityByYear(startYear, endYear);
    }

    @Override
    public Integer getPrivacySettingsById(Long userId) {
        return userMapper.getPrivacySettingsById(userId);
    }

}
